home *** CD-ROM | disk | FTP | other *** search
- Path: li.net!jeremy
- From: jeremy@newshost.li.net (Jeremy Markman)
- Newsgroups: comp.lang.c
- Subject: Re: Recursion
- Date: 4 Apr 1996 17:27:28 GMT
- Organization: LI Net (Long Island Network)
- Message-ID: <4k10q0$m5d@linet06.li.net>
- References: <31624BC2.70D2@sooner.net> <828548265snz@genesis.demon.co.uk>
- NNTP-Posting-Host: linet04.li.net
- X-Newsreader: TIN [version 1.2 PL2]
-
- Lawrence Kirby (fred@genesis.demon.co.uk) wrote:
-
- : I think you've picked a bad example. You really need an extra argument in
- : this case to pass on a running accumulator. A more suitable problem would
- : be to write a recursive function that is passed an integer (unsigned is
- : easiest) and writes the character representation to stdout.
- Absolutely WRONG. The whole point of recursion is that you do not need a
- running accumulator. When written correctly, the return value of each
- recursive loop will be the correct accumulated value. ANyhow, here is a
- better version of what I already posted...
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <math.h>
-
- int convert(char *string)
- {
- int value;
- int len = strlen(string);
-
- if (string[0] == '\0')
- return(0);
- value = convert(string+1);
- value += ((string[0] - '0') * pow(10,len-1));
- return(value);
- }
-
- void main()
- {
- char *string = "1234";
-
- printf("%d\n",convert(string));
- }
-